<?php

namespace app\api\controller;

use app\admin\model\Partynews as PartynewsMdl;

use think\Db;
use think\Exception;
use think\Request;

/**
 * 建党要闻
 */
class News extends BaseController
{

    /**
     * 获取列表
     */
    public function getList()
    {
        $param = self::getHttpParam();
        $start = 0;
        // 每页显示条数
        $length = 10;
        // 排序条件
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }
        if (empty($param->type)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 不能为空');
        }
        $where = [
            'a.type' => $param->type,
            'a.status' => 1
        ];
        $fiels = "a.id,a.title,a.imgUrl,a.createDate,d.name";
        $model = db('partynews');
        $result = $model->where($where)
            ->alias('a')
            ->join('user u','a.create_user_id = u.id')
            ->join('department d','u.departmentId = d.id')
            ->limit($start, $length)
            ->order('createDate desc')
            ->field($fiels)
            ->select();
        $where = [
            'type' => $param->type,
            'status' => 1
        ];
        $total = count($model->where($where)->select());
        if (empty($result)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到动态');
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 获取详情
     */
    public function getDetail()
    {
        $param = self::getHttpParam();
        if (empty($param->newId)){
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, 'newId 不能为空');
        }
        $id = $param->newId;

        $where = [
            'a.id'   => $id,
        ];
        $fiels = "a.id,a.title,a.imgUrl,a.detail,a.createDate,a.readCount,d.name";
        $model = db('partynews');
        $result = $model->where($where)
            ->alias('a')
            ->join('user u','a.create_user_id = u.id')
            ->join('department d','u.departmentId = d.id')
            ->order('createDate desc')
            ->field($fiels)
            ->find();

        if (empty($result)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到详情');
        }

        $result['readCount'] += 1;
        // 每查看一次，阅读数量加1
        PartynewsMdl::where('id', $id)->setInc('readCount');

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result);
    }
}